tags = (
'article', 'inproceedings', 'proceedings', 'book', 'phdthesis', 'mastersthesis', 'data', 'incollection', 'www', 'person')


def read(file_name):
    f = open(file_name, 'r')
    rows = f.readlines()
    f.close()
    return rows


def cut(file_name):
    rows = read(file_name)
    print("read() finished")
    head = rows[0] + rows[1] + rows[2]
    tail = '</dblp>'
    length = len(rows) - 1
    for i in range(0, 1):
        current_file = open('../data/dblp/dblp_' + str(i) + '.xml', 'w')
        start = i * 1000000 + 3
        end = min((i + 1) * 1000000 + 30, length - 1)
        if end <= start:
            break
        current_file.write(head)
        for j in range(start, end):
            current_file.write(rows[j])
        current_file.write(tail)
        current_file.close()
        print('cut(' + str(i) + ') [start=' + str(start) + ', end=' + str(end) + '] finished')


def soften(file_name):
    rows = read(file_name)
    print('read(' + file_name + ') finished')
    f = open(file_name, 'w')
    head = rows[0] + rows[1] + rows[2]
    tail = '</dblp>'
    length = len(rows) - 1
    start = 0
    end = 0
    for i in range(3, length):
        if rows[i].find('<booktitle>') > -1:
            continue
        for tag in tags:
            if rows[i].find('<' + tag) > -1:
                start = i
                rows[i] = rows[i][rows[i].find('<' + tag):]
                break
        if start != 0:
            break
    for j in range(length - 1, 2, -1):
        for tag in tags:
            if rows[j].find('</' + tag + '>') > -1:
                end = j
                rows[j] = rows[j][:rows[j].find('</' + tag + '>') + len('</' + tag + '>')]
                break
        if end != 0:
            break
    f.write(head)
    for k in range(start, end + 1):
        f.write(rows[k])
    f.write(tail)
    f.close()
    print('soften(' + file_name + ') finished')


if __name__ == '__main__':
    cut('../data/dblp/dblp_bak.xml')
    for p in range(54):
        # for p in range(1):
        soften('../data/dblp/dblp_' + str(p) + '.xml')
